<template>
    <div class="searchForm">
        <el-form @submit.prevent :inline="true" :model="formModel" label-width="120px" ref="formRef">
            <template v-for="(item, index) in fromList" :key="index">
                <el-form-item :label="item.label" v-if="item.type === 'input'" :prop="[item.field]">
                    <el-input v-model="formModel[item.field]" :placeholder="item.placeholder" />
                </el-form-item>
                <el-form-item :label="item.label" v-else-if="item.type === 'select'" :prop="[item.field]">
                    <el-select v-model="formModel[item.field]" :placeholder="item.placeholder">
                        <el-option v-for="it in item.option" :key="it.value" :label="it.label" :value="it.value" />
                    </el-select>
                </el-form-item>
                <el-form-item :label="item.label" v-else="item.type === 'datetimerange'" :prop="[item.field]">
                    <el-date-picker v-model="formModel[item.field]" type="datetimerange"
                        :start-placeholder="item.start_placeholder" :end-placeholder="item.end_placeholder"
                        :disabled-date="disabledDate" format="YYYY-MM-DD HH:mm:ss" date-format="YYYY/MM/DD ddd"
                        time-format="A hh:mm:ss" />
                </el-form-item>
            </template>
            <el-form-item>
                <slot name="buttons" :model="formModel" :formRef="formRef">
                    <el-button type="primary" @click="onSubmit(formRef)">{{ _options.submitButtonText }}</el-button>
                    <el-button v-if="_options.showResetButton" type="info" @click="resetForm(formRef)">
                        {{ _options.resetButtonText }}
                    </el-button>
                    <el-button v-if="_options.showCancelButton" @click="emit('cancel')">
                        {{ _options.cancelButtonText }}
                    </el-button>
                </slot>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
import { ref, computed } from 'vue'

const formModel = ref({})
const formRef = ref()
const emit = defineEmits(['submit', 'reset'])
defineExpose({
    formRef
})
const props = defineProps({
    fromList: Array,
    options: Object,
})
const _options = computed(() => {
    const option = {
        labelPosition: 'right',
        disabled: false,
        submitButtonText: '提交',
        resetButtonText: '重置',
        cancelButtonText: '取消'
    }
    return Object.assign(option, props?.options)
})
const onSubmit = (formEl) => {
    if (!formEl) return
    emit('submit', formModel.value)
}
const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
    emit('reset', formModel.value)
}
const disabledDate = (time) => {
    return time.getTime() > Date.now()
}
</script>

<style lang="less" scoped>
.searchForm {
    padding: 10px 0;
    background-color: #f0f0f0;
}
</style>
